<?php
namespace backend\models;

use yii\base\Model;
use common\models\User;
use yii\data\ActiveDataProvider;
use backend\models\UserInfo;

/**
 * Signup form
 */
class SignupForm extends Model
{
    public $username;
    public $password;
    public $avatar;
    public $isNewRecord = true;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['username', 'trim'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
            ['username', 'string', 'min' => 2, 'max' => 255],

            ['avatar', 'required'],
            ['password', 'required'],
            ['password', 'string', 'min' => 6],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if (!$this->validate()) {
            return null;
        }
        
        $user = new User();
        $userinfo = new UserInfo();
        $user->username = $this->username;
        $user->email = '';
        $user->setPassword($this->password);
        $user->generateAuthKey();

        if( $user->save() ){
            $userinfo->userid = $user->id;
            $userinfo->avatar = $this->avatar;
            $userinfo->save();

            return $user;
        }else{
            return null;
        }
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = User::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            return $dataProvider;
        }

        $query->andFilterWhere(['like', 'username', $this->username]);
            //->andFilterWhere(['like', 'email', $this->email]);
        return $dataProvider;
    }
}
